// pages/takePhoto/result/index.js
// wx.cloud.init({
//   env:'magic-2gl01tcyef44c307'
// })
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show:false,
    theme:getApp().globalData.presentTheme,
    themeName:getApp().globalData.presentTheme.midColor.match(/wux-(\S*)/)[1],
    avatar:getApp().globalData.userInfo.avatarUrl,
    nickname:getApp().globalData.userInfo.nickName,
    charge:false,
    visible1: true,
    visible2: false,
    skinData:'',
    skinGlobalData:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.book()
    let that = this
    // const eventCannel = this.getOpenerEventChannel()
    // eventCannel.on("face_list",res=>{
    //   console.log("来自 componText 页面的数据",res) //{ data: '我是来自 componText 页面的数据' }
    //   that.dealFaceInfo(res.data)
    // })
    wx.getStorage({
      key: 'skinData',
      success: function(res) {
        console.log("来自缓存的数据",res.data)
        that.setData({
          age:res.data.age,
          avatar:getApp().globalData.userInfo.avatarUrl,
          nickname:getApp().globalData.userInfo.nickName,
        })
        that.dealFaceInfo(res.data)
      },
    })

  },
  // "requestPayment:fail parameter error: parameter.timeStamp should be String instead of Undefined;parameter.nonceStr should be String instead of Undefined;parameter.package should be String instead of Undefined;parameter.signType should be String instead of Undefined;parameter.paySign should be String instead of Undefined;"
  pay:function(e){
    let orderid = this.randomWord()
    let that = this
    console.log(orderid)
    wx.cloud.callFunction({
      name: 'pay_test',
      data:{
        outTradeNo:orderid
      },
      success: res => {
        console.log(res)
        const payment = res.result.payment
        wx.requestPayment({
          ...payment,
          success (res) {
            console.log('pay success', res)
            let data = that.data.skinData
            data.outTradeNo = orderid
            db.collection("FaceInfo").add({
              data:data
            }).then(res=>{
              console.log(res)
              that.setData({
                charge:true
              })
            })
          },
          fail (err) {
            console.error('pay fail', err)
          }
        })
      },
      fail: console.error,
    })


  },

  randomWord() {
    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    var nums = ""
    for (var i = 0; i < 32; i++) {
      var id = parseInt(Math.random() * 61)
      nums += chars[id]
    }
    return nums
  },

  dealFaceInfo: function (info) {
    console.log(info)
    // 雷达图数据
    let list = [{
            'name': '光滑',
            'value': (info.skin.smooth / 4) * 100 + ''
        },
        {
            'name': '肤色',
            'value': (info.skin.color / 6) * 100 + ''
        },
        {
            'name': '痘痘',
            'value': info.acnespotmole.acbe_num == 0 ? "100" : (2.7 ** (-info.acnespotmole.acne_num)) * 100 + ''
        },
        {
            'name': '斑点',
            'value': (2.7 ** (-info.acnespotmole.speckle_num)) * 100 + ''
        },
        {
            'name': '皱纹',
            'value': (2.7 ** (-info.wrinkle.wrinkle_num)) * 100 + ''
        },
        {
            'name': '黑头',
            'value': info.blackheadpore.blackehead_num == 0 ? "100" : (2.7 ** (-info.blackheadpore.blackhead_num)) * 100 + ''
        },
    ]
    let radarList = {
        'name': '皮肤得分',
        list: list
    }



    // 各项指标评分
    let healthLevel = (info.acnespotmole.acbe_num == 0 ? 100 : (2.7 ** (-info.acnespotmole.acne_num)) * 100) * 0.5 +
        (2.7 ** (parseInt(-info.eyesattr.dark_circle_left.length == 0 ? 1 : -info.eyesattr.dark_circle_left[0].length)) +
            2.7 ** (parseInt(-info.eyesattr.dark_circle_right.length == 0 ? 1 : -info.eyesattr.dark_circle_right[0].length))
        ) / 2 * 100 * 0.25 +
        (2.7 ** parseInt(-info.eyesattr.eye_bags_left.length == 0 ? 0 : -info.eyesattr.eye_bags_left[0].length) +
            2.7 ** (parseInt(-info.eyesattr.eye_bags_right == 0 ? 0 : -info.eyesattr.eye_bags_right[0].length))) / 2 * 100 * 0.25
    let dryLevel = (1 - (info.skinquality.skin_dryoil_check.reduce((total, currentValue, index, arr) => {
        return total + parseInt(currentValue)
    }, 0) / 10)) * 100
    let smooth = ((info.skin.smooth / 4) * 100)
    let youngLevel = (2.7 ** (-info.wrinkle.wrinkle_num)) * 100
    let score = (healthLevel + dryLevel + smooth + youngLevel) / 4

    let skinData = {
        "radarList": radarList,
        "score": score.toFixed(2),
        "healthLevel": healthLevel.toFixed(2),
        "smoothLevel": smooth.toFixed(2),
        "dryLevel": dryLevel.toFixed(2),
        "youngLevel": youngLevel.toFixed(2),
        "count": this.data.count,
        "age":this.data.age
    }

    this.setData({
        skinData: skinData,
        skinGlobalData: this.data.skinGlobalData.concat(skinData)
    })



},




  // book: function (e) {
  //   let that = this
  //   wx.request({
  //     url: 'http://pv.sohu.com/cityjson?ie=utf-8',
  //     success:res=>{
  //       console.log(res)
  //       var aaa = res.data.split(' ');
  //       var bbb=aaa[4]
  //       var ccc = bbb.replace('"','')
  //       var ddd = ccc.replace('"', '')
  //       let ip = ddd.replace(',', '')



  //       let url = "https://api.mch.weixin.qq.com/pay/unifiedorder"
  //       let options = {
  //         appid: "wx485412291c7b9227",
  //         mch_id: "1625399850",
  //         nonce_str: this.randomWord(),
  //         sign:"",
  //         body:"AI测肤",
  //         out_trade_no:this.randomWord(),
  //         total_fee:1,
  //         spbill_create_ip:ip,
  //         time_expire:"20200505220000"
  //       }
    
    
  //       wx.request({
  //         url: url,
  //         method: "POST",
  //         data: "",
  //         success: res => {
  //           console.log(res)
  //         },
  //         fail: err => {
  //           console.log(err)
  //         }
  //       })


  //     }
  //   })


  // },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  refuse(){
    wx.navigateBack({
      delta: 1,
    })
  }
})